package fr.utbm.aiechat;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class Localisation extends AsyncTask<String, Integer, String> {
    public double lat = 0.0;
    public double lng = 0.0;

    public LocationManager mLocationManager;
    public VeggsterLocationListener mVeggsterLocationListener;
    private final Context context;
    private LocalisationData LocalisationData;

    public Localisation(Context applicationContext) {
		// TODO Auto-generated constructor stub
		context = applicationContext;
		
	}

    @Override
    protected void onPreExecute() {
        mVeggsterLocationListener = new VeggsterLocationListener();
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,mVeggsterLocationListener);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mVeggsterLocationListener);
        
        LocalisationData = fr.utbm.aiechat.LocalisationData.getInstance();
    }

    protected void onPostExecute(String result) {
       /*Toast.makeText(context,
                "LATITUDE :" + lat+ " LONGITUDE :" + lng,
                Toast.LENGTH_LONG).show();
       System.out.println("LATITUDE :" + lat + " LONGITUDE :" + lng);
       */
       LocalisationData.setLat(lat);
       LocalisationData.setLng(lng);
       //System.out.println("latSET:"+LocalisationData.getLat()+" lngSET:"+LocalisationData.getLng());
       Network.getInstance().sendPosition();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        while (this.lat == 0.0) {

        }
        return null;
    }

    public class VeggsterLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            try {
                lat = location.getLatitude();
                lng = location.getLongitude();
//                LocalisationData.setLat(location.getLatitude());
  //              LocalisationData.setLng(location.getLongitude());

            } catch (Exception e) {
            	
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.i("OnProviderDisabled", "OnProviderDisabled");
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.i("onProviderEnabled", "onProviderEnabled");
        }

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
            Log.i("onStatusChanged", "onStatusChanged");

        }

    }
}